local addon, ns = ...
local C = ns.shared.color
local L = ns.L

local unreadMail = false


local mail_events = {
	"UPDATE_PENDING_MAIL",
	"MAIL_INBOX_UPDATE",
	"MAIL_CLOSED",
	"PLAYER_LOGIN",
	"PLAYER_ENTERING_WORLD",
	"MAIL_SHOW",
}


local mail_init = function()
	MiniMapMailFrame:Hide()
	MiniMapMailFrame.Show = dummyFunc

	if Broker_EverythingDB[L["Mail"]].playsound == nil then
		Broker_EverythingDB[L["Mail"]].playsound = false
	end
end

		
local mail_onevent = function(self, event)
	local dataobj = self.obj  or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["MAIL"])
	local newMail = false
	
	if event == "UPDATE_PENDING_MAIL" or event == "PLAYER_ENTERING_WORLD" or event =="PLAYER_LOGIN" then
		newMail = HasNewMail() 
		
		if unreadMail ~= newMail then
			if newMail and Broker_EverythingDB[L["Mail"]].playsound == true then
				PlaySoundFile("Interface\\Addons\\Broker_Everything\\media\\mailalert.mp3", "Master")
			end
			unreadMail = newMail
		end
	
		self:UnregisterEvent("PLAYER_ENTERING_WORLD")
		self:UnregisterEvent("PLAYER_LOGIN")
	end
	
	if event == "MAIL_INBOX_UPDATE" or event == "MAIL_SHOW" or event == "MAIL_CLOSED" then
		for i = 1, GetInboxNumItems() do
			local _, _, _, _, _, _, _, _, wasRead = GetInboxHeaderInfo(i);
			if( not wasRead ) then
				newMail = true;
				break;
			end
		end
	end
	
	if newMail then
		dataobj.text = C.dkgreen(L["New Mail"])
		dataobj.icon = "Interface\\Addons\\Broker_Everything\\media\\mail_new"
	else
		dataobj.text = L["No Mail"]
		dataobj.icon = "Interface\\Addons\\Broker_Everything\\media\\mail_none"
	end

end


local mail_tooltip = function(t)

	local sender1, sender2, sender3 = GetLatestThreeSenders()
	t:AddLine(L["Mail"])

	t:AddLine(" ")
	if not sender1 then
		t:AddLine(L["No Mail"])
		return
	end

	t:AddLine(L["Mail From"])
	t:AddLine(sender1)

	if sender2 then t:AddLine(sender2) end
	if sender3 then t:AddLine(sender3) end
	


end



Broker_Everything:Register(L["Mail"],
	"Interface\\Addons\\Broker_Everything\\media\\mail_none",
	mail_init,
	mail_onevent,
	mail_events,
	0,
	mail_tooltip,
	nil,
	nil)
